<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>评论分析</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <script src="https://cdn.bootcdn.net/ajax/libs/echarts/5.4.3/echarts.min.js"></script>
    <script src="https://cdn.bootcdn.net/ajax/libs/echarts-wordcloud/2.0.0/echarts-wordcloud.min.js"></script>
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                        bilibili: {
                            pink: '#FB7299',
                            blue: '#23ADE5',
                            dark: '#18191C',
                        }
                    },
                    fontFamily: {
                        sans: ['"HarmonyOS Sans"', 'sans-serif'],
                    }
                }
            }
        }
    </script>
    <style>
        @import url('https://fonts.googleapis.com/css2?family=Noto+Sans+SC:wght@400;500;700&display=swap');

        body {
            font-family: 'Noto Sans SC', sans-serif;
            background-color: #f5f5f5;
        }

        .gradient-bg {
            background: linear-gradient(135deg, #23ADE5 0%, #FB7299 100%);
        }

        .card-hover {
            transition: all 0.3s ease;
        }

        .card-hover:hover {
            transform: translateY(-5px);
            box-shadow: 0 10px 25px rgba(0, 0, 0, 0.1);
        }

        .level-badge {
            display: inline-flex;
            align-items: center;
            justify-content: center;
            width: 24px;
            height: 24px;
            border-radius: 50%;
            color: white;
            font-size: 12px;
            font-weight: bold;
            margin-right: 5px;
        }

        .level-1 { background-color: #cccccc; }
        .level-2 { background-color: #99cc66; }
        .level-3 { background-color: #3399ff; }
        .level-4 { background-color: #9966cc; }
        .level-5 { background-color: #ff9900; }
        .level-6 { background-color: #ff6666; }

        .chart-container {
            width: 100%;
            height: 400px;
        }

        .loading-spinner {
            border: 4px solid rgba(0, 0, 0, 0.1);
            border-radius: 50%;
            border-top: 4px solid #FB7299;
            width: 40px;
            height: 40px;
            animation: spin 1s linear infinite;
            margin: 20px auto;
        }

        .comment-card {
            background-color: white;
            border-radius: 8px;
            padding: 16px;
            margin-bottom: 16px;
            box-shadow: 0 2px 8px rgba(0,0,0,0.05);
        }

        .reply-card {
            background-color: #f9f9f9;
            border-left: 3px solid #FB7299;
            margin-left: 20px;
            margin-top: 8px;
        }

        .comment-header {
            display: flex;
            margin-bottom: 12px;
        }
        .comment-user {
            font-weight: 600;
            color: #333;
        }
        .comment-content {
            color: #333;
            line-height: 1.6;
            margin-bottom: 12px;
        }
        .comment-footer {
            display: flex;
            align-items: center;
            font-size: 14px;
            color: #666;
        }
        .comment-like {
            margin-right: 16px;
        }

        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }
    </style>
</head>
<body class="bg-gray-100">
<div class="min-h-screen">

    <nav class="bg-white shadow-sm">
        <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
            <div class="flex justify-between h-16">
                <div class="flex items-center">
                    <div class="flex-shrink-0 flex items-center cursor-pointer hover:opacity-80 transition-opacity duration-200"
                         onclick="window.location.href = 'main'"
                         title="返回主页">
                        <i class="fab fa-bilibili text-3xl text-bilibili-pink hover:scale-105 transition-transform"></i>
                        <span class="ml-2 text-xl font-bold text-gray-800 hover:text-bilibili-pink transition-colors">视频评论</span>
                    </div>
                </div>
                <div class="flex items-center">
                    <a  onclick="window.location.href=`video?bvid=${bvid}`" class="text-gray-600 hover:text-bilibili-pink mr-4">
                        <i class="fas fa-arrow-left mr-1"></i>返回视频页
                    </a>
                </div>
            </div>
        </div>
    </nav>


    <main class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
        <!-- 视频基本信息 -->
        <div class="bg-white rounded-xl shadow-md overflow-hidden mb-8">
            <div class="p-6">
                <div class="flex flex-col md:flex-row justify-between items-start">
                    <div class="flex-1">
                        <h1 id="videoTitle" class="text-2xl font-bold text-gray-800 mb-2">加载中...</h1>
                        <div class="flex flex-wrap items-center text-sm text-gray-500 mb-4 gap-4">
                            <span><i class="fas fa-play mr-1"></i> 播放量: <span id="videoViews">加载中...</span></span>
                            <span><i class="fas fa-heart mr-1"></i> 点赞数: <span id="videoLikes">加载中...</span></span>
                            <span><i class="fas fa-comment-dots mr-1"></i> 评论数: <span id="videoComments">加载中...</span></span>
                        </div>
                        <div class="text-sm text-gray-600">
                            <p>UP主: <span id="videoAuthor" class="text-bilibili-blue" >加载中...</span></p>
                        </div>
                    </div>
                    <button id="videoLinkBtn" class="mt-4 md:mt-0 bg-bilibili-pink hover:bg-bilibili-blue text-white font-medium py-2 px-4 rounded-lg transition-all duration-300 flex items-center">
                        <i class="fas fa-external-link-alt mr-2"></i>
                        观看视频
                    </button>
                </div>
            </div>
        </div>

        <!-- 评论分析 -->
        <div class="grid grid-cols-1 md:grid-cols-3 gap-6 mb-8">
            <div class="bg-white rounded-xl shadow-md overflow-hidden card-hover">
                <div class="p-6">
                    <div class="flex items-center">
                        <div class="p-3 rounded-full bg-blue-100 text-bilibili-blue">
                            <i class="fas fa-comments text-xl"></i>
                        </div>
                        <div class="ml-4">
                            <p class="text-sm font-medium text-gray-500">总评论数</p>
                            <p id="totalComments" class="text-2xl font-semibold text-gray-900">加载中...</p>
                        </div>
                    </div>
                </div>
            </div>

            <div class="bg-white rounded-xl shadow-md overflow-hidden card-hover">
                <div class="p-6">
                    <div class="flex items-center">
                        <div class="p-3 rounded-full bg-pink-100 text-bilibili-pink">
                            <i class="fas fa-thumbs-up text-xl"></i>
                        </div>
                        <div class="ml-4">
                            <p class="text-sm font-medium text-gray-500">最高赞评论</p>
                            <p id="topLikedComment" class="text-2xl font-semibold text-gray-900">加载中...</p>
                        </div>
                    </div>
                </div>
            </div>

            <div class="bg-white rounded-xl shadow-md overflow-hidden card-hover">
                <div class="p-6">
                    <div class="flex items-center">
                        <div class="p-3 rounded-full bg-purple-100 text-purple-600">
                            <i class="fas fa-user-friends text-xl"></i>
                        </div>
                        <div class="ml-4">
                            <p class="text-sm font-medium text-gray-500">活跃用户</p>
                            <p id="activeUser" class="text-2xl font-semibold text-gray-900">加载中...</p>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- 评论列表 -->
        <div class="bg-white rounded-xl shadow-md overflow-hidden card-hover mb-8">
            <div class="p-6">
                <div class="flex flex-col md:flex-row justify-between items-start md:items-center mb-6">
                    <h2 class="text-lg font-semibold text-gray-800 mb-4 md:mb-0">评论列表</h2>
                    <div class="flex space-x-4">
                        <button id="updateCommentsBtn"
                                class="bg-bilibili-blue hover:bg-bilibili-pink text-white font-medium py-2 px-4 rounded-lg transition-all duration-300 flex items-center">
                            <i class="fas fa-sync-alt mr-2"></i>
                            更新评论数据
                        </button>
                        <div class="relative w-full md:w-64">
                            <input type="text" id="commentSearch" placeholder="搜索评论..." class="w-full pl-10 pr-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-bilibili-pink focus:border-transparent">
                            <i class="fas fa-search absolute left-3 top-3 text-gray-400"></i>
                        </div>
                    </div>
                </div>

                <div id="commentList">
                    <div class="loading-spinner"></div>
                </div>

                <!-- 分页控件 -->
                <div class="flex flex-col sm:flex-row justify-between items-center mt-6">
                    <div class="text-sm text-gray-600 mb-4 sm:mb-0">
                        <!--                        显示 <span id="commentStartItem">1</span> - <span id="commentEndItem">10</span> 条，共 <span id="commentTotalItems">0</span> 条-->
                    </div>
                    <div class="flex space-x-2">
                        <button id="commentPrevPage" class="px-4 py-2 border border-gray-300 rounded-lg bg-white text-gray-700 hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed" disabled>
                            <i class="fas fa-chevron-left mr-1"></i>上一页
                        </button>
                        <div class="flex items-center">
                            <span id="commentCurrentPage">1</span>
                            <span class="mx-1">/</span>
                            <span id="commentTotalPages">1</span>
                        </div>
                        <button id="commentNextPage" class="px-4 py-2 border border-gray-300 rounded-lg bg-white text-gray-700 hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed" disabled>
                            下一页<i class="fas fa-chevron-right ml-1"></i>
                        </button>
                    </div>
                </div>
            </div>
        </div>

        <!-- 情感分析 -->
        <div class="bg-white rounded-xl shadow-md overflow-hidden card-hover mb-8">
            <div class="p-6">
                <h2 class="text-lg font-semibold text-gray-800 mb-4">评论情感分析</h2>
                <div id="sentimentChart" class="chart-container">
                    <div class="loading-spinner"></div>
                </div>
            </div>
        </div>

        <!-- 词频 -->
        <div class="bg-white rounded-xl shadow-md overflow-hidden card-hover mb-8">
            <div class="p-6">
                <h2 class="text-lg font-semibold text-gray-800 mb-4">评论热词分析</h2>
                <div id="wordCloudChart" class="chart-container">
                    <div class="loading-spinner"></div>
                </div>
            </div>
        </div>

        <!-- 分析结果 -->
        <div class="bg-white rounded-xl shadow-md overflow-hidden card-hover mb-8">
            <div class="p-6">
                <h2 class="text-lg font-semibold text-gray-800 mb-4">评论数据分析结果</h2>
                <div id="analysisResult" class="bg-gray-50 p-4 rounded-lg">
                    <div class="loading-spinner"></div>
                </div>
            </div>
        </div>
    </main>
</div>

<script>
    const url = new URL(window.location.href);
    const params = new URLSearchParams(url.search);
    const bvid = params.get('bvid');

    if (!bvid) {
        alert(`未获取到bv号，请确认是否已输入`);
        window.location.href = `main`;
    }

    async function fetchVideoData() {
        try {
            const response = await fetch(`http://localhost:8080/v1/video/query/${bvid}`, {
                method: 'POST'
            });
            const data = await response.json();

            if (data.code % 2 === 0) {
                return data.data;
            } else {
                console.error('获取视频数据失败:', data.msg, data.data);
                document.getElementById('videoTitle').textContent = '数据加载失败';
                document.getElementById('videoTitle').nextElementSibling.innerHTML =
                    `<div class="text-red-500">${data.msg}: ${data.data}</div>`;
                return null;
            }
        } catch (error) {
            console.error('获取视频数据失败:', error);
            document.getElementById('videoTitle').textContent = '数据加载失败';
            document.getElementById('videoTitle').nextElementSibling.innerHTML =
                '<div class="text-red-500">网络请求失败，请检查网络连接</div>';
            return null;
        }
    }

    async function fetchCommentData() {
        try {
            const response = await fetch(`http://localhost:8080/v1/comment/query/${bvid}`, {
                method: 'POST'
            });
            const data = await response.json();

            if (data.code % 2 === 0) {
                return data.data;
            } else {
                console.error('获取评论数据失败:', data.msg, data.data);
                document.getElementById('commentList').innerHTML =
                    `<div class="text-red-500 p-4">${data.msg}: ${data.data}</div>`;
                return null;
            }
        } catch (error) {
            console.error('获取评论数据失败:', error);
            document.getElementById('commentList').innerHTML =
                '<div class="text-red-500 p-4">网络请求失败，请检查网络连接</div>';
            return null;
        }
    }

    function formatNumber(num) {
        if (typeof num !== 'number') {
            num = parseInt(num) || 0;
        }
        return num.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
    }

    async function fetchSentimentData() {
        try {
            const response = await fetch(`http://localhost:8080/v1/comment/emo/${bvid}`, {
                method: 'POST'
            });
            const data = await response.json();

            if (data.code % 2 === 0) {
                return data.data;
            } else {
                console.error('获取情感分析数据失败:', data.msg, data.data);
                return null;
            }
        } catch (error) {
            console.error('获取情感分析数据失败:', error);
            return null;
        }
    }

    async function fetchWordCloudData() {
        try {
            const response = await fetch(`http://localhost:8080/v1/comment/segmenter/${bvid}`, {
                method: 'POST'
            });
            const data = await response.json();

            if (data.code % 2 === 0) {
                return data.data;
            } else {
                console.error('获取词云数据失败:', data.msg, data.data);
                return null;
            }
        } catch (error) {
            console.error('获取词云数据失败:', error);
            return null;
        }
    }

    function initSentimentChart(data) {
        const chart = echarts.init(document.getElementById('sentimentChart'));

        if (!data) {
            document.getElementById('sentimentChart').innerHTML =
                '<div class="text-gray-500 p-4 text-center">暂无情感分析数据</div>';
            return;
        }

        const total = data.积极 + data.中立 + data.消极;
        const positivePercent = Math.round((data.积极 / total) * 100);
        const neutralPercent = Math.round((data.中立 / total) * 100);
        const negativePercent = Math.round((data.消极 / total) * 100);

        const option = {
            tooltip: {
                trigger: 'item',
                formatter: '{a} <br/>{b}: {c} ({d}%)'
            },
            legend: {
                orient: 'vertical',
                right: 10,
                top: 'center',
                data: ['积极', '中立', '消极'],
                textStyle: {
                    color: '#666'
                }
            },
            series: [
                {
                    name: '情感分析',
                    type: 'pie',
                    radius: ['50%', '70%'],
                    avoidLabelOverlap: false,
                    itemStyle: {
                        borderRadius: 10,
                        borderColor: '#fff',
                        borderWidth: 2
                    },
                    label: {
                        show: false,
                        position: 'center'
                    },
                    emphasis: {
                        label: {
                            show: true,
                            fontSize: '18',
                            fontWeight: 'bold'
                        }
                    },
                    labelLine: {
                        show: false
                    },
                    data: [
                        {
                            value: data.积极,
                            name: `积极 (${positivePercent}%)`,
                            itemStyle: { color: '#4ade80' }
                        },
                        {
                            value: data.中立,
                            name: `中立 (${neutralPercent}%)`,
                            itemStyle: { color: '#60a5fa' }
                        },
                        {
                            value: data.消极,
                            name: `消极 (${negativePercent}%)`,
                            itemStyle: { color: '#f87171' }
                        }
                    ]
                }
            ]
        };

        chart.setOption(option);

        window.addEventListener('resize', function() {
            chart.resize();
        });
    }

    function initWordCloudChart(data) {
        const chart = echarts.init(document.getElementById('wordCloudChart'));

        if (!data) {
            document.getElementById('wordCloudChart').innerHTML =
                '<div class="text-gray-500 p-4 text-center">暂无热词分析数据</div>';
            return;
        }

        const wordCloudData = Object.entries(data).map(([name, value]) => ({
            name,
            value
        }));

        const option = {
            backgroundColor: '#ffffff',
            tooltip: {},
            series: [{
                type: 'wordCloud',
                shape: 'circle',
                left: 'center',
                top: 'center',
                width: '90%',
                height: '90%',
                right: null,
                bottom: null,
                sizeRange: [12, 60],
                rotationRange: [-45, 45],
                rotationStep: 15,
                gridSize: 8,
                drawOutOfBound: false,
                textStyle: {
                    fontFamily: 'Noto Sans SC',
                    fontWeight: 'bold',
                    color: function () {
                        return 'rgb(' +
                            Math.round(Math.random() * 155 + 100) + ',' +
                            Math.round(Math.random() * 155 + 100) + ',' +
                            Math.round(Math.random() * 155 + 100) + ')';
                    }
                },
                emphasis: {
                    focus: 'self',
                    textStyle: {
                        shadowBlur: 10,
                        shadowColor: '#333'
                    }
                },
                data: wordCloudData
            }]
        };

        chart.setOption(option);

        window.addEventListener('resize', function() {
            chart.resize();
        });
    }

    class CommentListManager {
        constructor() {
            this.allComments = [];
            this.filteredComments = [];
            this.currentPage = 1;
            this.itemsPerPage = 10;
            this.searchTerm = '';

            this.initElements();
            this.bindEvents();
        }

        initElements() {
            this.elements = {
                commentList: document.getElementById('commentList'),
                commentSearch: document.getElementById('commentSearch'),
                commentSort: document.getElementById('commentSort'),
                commentPrevPage: document.getElementById('commentPrevPage'),
                commentNextPage: document.getElementById('commentNextPage'),
                commentCurrentPage: document.getElementById('commentCurrentPage'),
                commentTotalPages: document.getElementById('commentTotalPages'),
                // commentStartItem: document.getElementById('commentStartItem'),
                // commentEndItem: document.getElementById('commentEndItem'),
                // commentTotalItems: document.getElementById('commentTotalItems')
            };
        }

        bindEvents() {
            this.elements.commentSearch.addEventListener('input', (e) => {
                this.searchTerm = e.target.value.toLowerCase();
                this.currentPage = 1;
                this.filterComments();
                this.render();
            });

            this.elements.commentPrevPage.addEventListener('click', () => {
                if (this.currentPage > 1) {
                    this.currentPage--;
                    this.render();
                }
            });

            this.elements.commentNextPage.addEventListener('click', () => {
                if (this.currentPage < this.getTotalPages()) {
                    this.currentPage++;
                    this.render();
                }
            });

            document.getElementById('updateCommentsBtn').addEventListener('click', async () => {
                try {
                    const button = document.getElementById('updateCommentsBtn');
                    button.disabled = true;
                    button.innerHTML = '<i class="fas fa-spinner fa-spin mr-2"></i>更新中...';

                    const response = await fetch(`http://localhost:8080/v1/comment/update/${bvid}`, {
                        method: 'POST'
                    });
                    const data = await response.json();

                    if (data.code % 2 === 0) {
                        this.loadComments(data.data);
                        const successMsg = document.createElement('div');
                        successMsg.className = 'text-green-500 text-sm mt-2';
                        successMsg.textContent = '评论更新成功！';
                        button.parentNode.appendChild(successMsg);
                        setTimeout(() => successMsg.remove(), 3000);
                    } else {
                        console.error('更新评论失败:', data.msg, data.data);
                        alert(`更新评论失败: ${data.msg}`);
                    }
                } catch (error) {
                    console.error('更新评论失败:', error);
                    alert('网络请求失败，请检查网络连接');
                } finally {
                    const button = document.getElementById('updateCommentsBtn');
                    button.disabled = false;
                    button.innerHTML = '<i class="fas fa-sync-alt mr-2"></i>更新评论数据';
                }
            });
        }

        loadComments(commentsData) {
            if (!commentsData) {
                this.allComments = [];
                this.filteredComments = [];
                this.render();
                return;
            }

            const commentsMap = {};
            const topLevelComments = [];

            if (commentsData.comment) {
                commentsData.comment.forEach(comment => {
                    const formattedComment = {
                        id: comment.id,
                        content: comment.content,
                        user: comment.username || '匿名用户',
                        level: comment.level || 1,
                        likes: comment.likeCount || 0,
                        gender: comment.gender || '保密',
                        isTopLevel: true,
                        replies: []
                    };

                    commentsMap[comment.id] = formattedComment;
                    topLevelComments.push(formattedComment);
                });
            }
            if (commentsData.replyComment) {
                commentsData.replyComment.forEach(reply => {
                    const formattedReply = {
                        id: reply.id,
                        content: reply.content,
                        user: reply.username || reply.user || '匿名用户',
                        level: reply.level || 1,
                        likes: reply.likeCount || 0,
                        gender: reply.gender || '保密',
                        isTopLevel: false,
                        parentId: reply.rid
                    };

                    if (commentsMap[reply.rid]) {
                        commentsMap[reply.rid].replies.push(formattedReply);
                    } else {
                        formattedReply.isTopLevel = true;
                        topLevelComments.push(formattedReply);
                    }
                });
            }

            this.allComments = topLevelComments;
            this.filteredComments = [...this.allComments];
            this.sortComments();
            this.render();

            this.updateStats(commentsData);
        }

        updateStats(commentsData) {
            if (!commentsData) return;

            let topLikedComment = null;
            let maxLikes = 0;

            if (commentsData.comment && commentsData.comment.length > 0) {
                commentsData.comment.forEach(comment => {
                    if (comment.likeCount > maxLikes) {
                        maxLikes = comment.likeCount;
                        topLikedComment = comment;
                    }
                });
            }

            if (commentsData.replyComment && commentsData.replyComment.length > 0) {
                commentsData.replyComment.forEach(reply => {
                    if (reply.likeCount > maxLikes) {
                        maxLikes = reply.likeCount;
                        topLikedComment = reply;
                    }
                });
            }

            if (topLikedComment) {
                document.getElementById('topLikedComment').textContent =
                    `${topLikedComment.content.substring(0, 30)}${topLikedComment.content.length > 30 ? '...' : ''} (点赞: ${formatNumber(topLikedComment.likeCount)})`;
            } else {
                document.getElementById('topLikedComment').textContent = '暂无数据';
            }

            const userCounts = {};

            if (commentsData.comment) {
                commentsData.comment.forEach(comment => {
                    if (comment.username) {
                        userCounts[comment.username] = (userCounts[comment.username] || 0) + 1;
                    }
                });
            }

            if (commentsData.replyComment) {
                commentsData.replyComment.forEach(reply => {
                    const username = reply.username || reply.user;
                    if (username) {
                        userCounts[username] = (userCounts[username] || 0) + 1;
                    }
                });
            }

            let activeUser = null;
            let maxCount = 0;
            for (const [username, count] of Object.entries(userCounts)) {
                if (count > maxCount) {
                    maxCount = count;
                    activeUser = username;
                }
            }

            if (activeUser) {
                document.getElementById('activeUser').textContent = `${activeUser} (评论: ${maxCount}条)`;
            } else {
                document.getElementById('activeUser').textContent = '暂无数据';
            }
        }

        filterComments() {
            if (this.searchTerm === '') {
                this.filteredComments = [...this.allComments];
            } else {
                this.filteredComments = this.allComments.filter(comment =>
                    comment.content.toLowerCase().includes(this.searchTerm) ||
                    comment.user.toLowerCase().includes(this.searchTerm)
                );
            }
            this.sortComments();
        }

        sortComments() {
            this.filteredComments.sort((a, b) => b.likes - a.likes);
        }

        getTotalPages() {
            return Math.ceil(this.filteredComments.length / this.itemsPerPage);
        }

        getPaginatedComments() {
            const start = (this.currentPage - 1) * this.itemsPerPage;
            const end = start + this.itemsPerPage;
            return this.filteredComments.slice(start, end);
        }

        render() {
            const paginatedComments = this.getPaginatedComments();
            const totalPages = this.getTotalPages();

            if (paginatedComments.length === 0) {
                this.elements.commentList.innerHTML = '<div class="text-gray-500 p-4 text-center">暂无评论数据</div>';
            } else {
                this.elements.commentList.innerHTML = paginatedComments.map(comment => {
                    let html = `
                        <div class="comment-card">
                            <div class="comment-header">
                                <span class="comment-user">${comment.user}</span>
                                <span class="level-badge level-${comment.level}">${comment.level}</span>
                                ${comment.gender === '男' ?
                        '<i class="fas fa-mars ml-2 text-blue-500"></i>' :
                        comment.gender === '女' ?
                            '<i class="fas fa-venus ml-2 text-pink-500"></i>' : ''}
                                <span class="ml-2 text-xs text-gray-500">${comment.isTopLevel ? '一级评论' : '回复评论'}</span>
                            </div>
                            <div class="comment-content">
                                ${comment.content}
                            </div>
                            <div class="comment-footer">
                                <span class="comment-like"><i class="fas fa-thumbs-up mr-1"></i> ${formatNumber(comment.likes)}</span>
                            </div>
                    `;

                    if (comment.replies && comment.replies.length > 0) {
                        html += `<div class="mt-2">`;
                        comment.replies.forEach(reply => {
                            html += `
                                <div class="reply-card">
                                    <div class="comment-header">
                                        <span class="comment-user">${reply.user}</span>
                                        <span class="level-badge level-${reply.level}">${reply.level}</span>
                                        ${reply.gender === '男' ?
                                '<i class="fas fa-mars ml-2 text-blue-500"></i>' :
                                reply.gender === '女' ?
                                    '<i class="fas fa-venus ml-2 text-pink-500"></i>' : ''}
                                        <span class="ml-2 text-xs text-gray-500">回复</span>
                                    </div>
                                    <div class="comment-content">
                                        ${reply.content}
                                    </div>
                                    <div class="comment-footer">
                                        <span class="comment-like"><i class="fas fa-thumbs-up mr-1"></i> ${formatNumber(reply.likes)}</span>
                                    </div>
                                </div>
                            `;
                        });
                        html += `</div>`;
                    }

                    html += `</div>`;
                    return html;
                }).join('');
            }

            this.elements.commentCurrentPage.textContent = this.currentPage;
            this.elements.commentTotalPages.textContent = totalPages;

            const startItem = (this.currentPage - 1) * this.itemsPerPage + 1;
            const endItem = Math.min(startItem + this.itemsPerPage - 1, this.filteredComments.length);

            this.elements.commentPrevPage.disabled = this.currentPage <= 1;
            this.elements.commentNextPage.disabled = this.currentPage >= totalPages;
        }
    }
    async function loadAllData() {
        const commentListManager = new CommentListManager();

        try {
            const videoData = await fetchVideoData();
            if (videoData) {
                document.getElementById('videoTitle').textContent = videoData.title || '无标题';
                document.getElementById('videoViews').textContent = formatNumber(videoData.playCount);
                document.getElementById('videoLikes').textContent = formatNumber(videoData.likeCount);
                document.getElementById('videoComments').textContent = formatNumber(videoData.commentCount);
                document.getElementById('totalComments').textContent = formatNumber(videoData.commentCount);
                document.getElementById('videoAuthor').textContent = videoData.username || '匿名用户';

                document.getElementById('videoLinkBtn').addEventListener('click', function() {
                    window.open(`https://www.bilibili.com/video/${videoData.bv}`, '_blank');
                });
            }

            // 评论
            const commentData = await fetchCommentData();
            commentListManager.loadComments(commentData);

            // 情感分析
            const sentimentData = await fetchSentimentData();
            initSentimentChart(sentimentData);

            // 词云
            const wordCloudData = await fetchWordCloudData();
            initWordCloudChart(wordCloudData);

            // 分析
            const analysisContainer = document.getElementById('analysisResult');
            analysisContainer.innerHTML = '';

            if (!commentData) {
                analysisContainer.innerHTML = '<p class="text-gray-600">没有评论数据可供分析</p>';
                return;
            }

            let positivePercent = 0;
            let neutralPercent = 0;
            let negativePercent = 0;
            let totalSentiment = 0;

            if (sentimentData) {
                totalSentiment = sentimentData.积极 + sentimentData.中立 + sentimentData.消极;
                positivePercent = totalSentiment > 0 ? Math.round((sentimentData.积极 / totalSentiment) * 100) : 0;
                neutralPercent = totalSentiment > 0 ? Math.round((sentimentData.中立 / totalSentiment) * 100) : 0;
                negativePercent = totalSentiment > 0 ? Math.round((sentimentData.消极 / totalSentiment) * 100) : 0;
            }
            let topKeywords = '无数据';
            if (wordCloudData && Object.keys(wordCloudData).length > 0) {
                topKeywords = Object.entries(wordCloudData)
                    .sort((a, b) => b[1] - a[1])
                    .slice(0, 5)
                    .map(item => item[0])
                    .join('、');
            }

            const allComments = [...(commentData.comment || []), ...(commentData.replyComment || [])];
            const totalLikes = allComments.reduce((sum, comment) => sum + (comment.likeCount || 0), 0);
            const avgLikes = allComments.length > 0 ? Math.round(totalLikes / allComments.length) : 0;
            const replyRatio = commentData.comment?.length > 0
                ? Math.round((commentData.replyComment?.length || 0) / commentData.comment.length * 100)
                : 0;

            const userActivity = {};
            allComments.forEach(comment => {
                const username = comment.username || comment.user || '匿名用户';
                userActivity[username] = (userActivity[username] || 0) + 1;
            });

            const activeUsers = Object.entries(userActivity)
                .sort((a, b) => b[1] - a[1])
                .slice(0, 3);

            const analysisReport = [
                `📊 情感分布: 积极 ${positivePercent}% | 中立 ${neutralPercent}% | 消极 ${negativePercent}%`,
                `🔍 热门关键词: ${topKeywords}`,
                `👥 活跃用户: ${activeUsers.map(user => `${user[0]}(${user[1]}条)`).join('、')}`,
                `${getResults(positivePercent, negativePercent, totalComments)}`
            ];


            analysisReport.forEach(item => {
                const p = document.createElement('p');
                p.className = 'text-gray-600 mb-3';
                p.innerHTML = item;
                analysisContainer.appendChild(p);
            });


            function getResults(positivePercent, negativePercent, totalComments) {
                let results = [];

                if (positivePercent < 30 && negativePercent > 35) {
                    results.push('该视频议题存在争议，其观点或讨论对象可能不符合主流');
                }

                if (replyRatio > 40 && totalComments>70) {
                    results.push('观众讨论兴致较高');
                }

                return results.length > 0 ? results.join('') : '';
            }

        } catch (error) {
            console.error('加载数据失败:', error);
        }
    }

    window.addEventListener('load', loadAllData);
</script>
</body>
</html>